package com.kdg.thread;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

/**
 * 死锁检查类（守护进程）
 * @author kdg
 * @description:
 * @date 2018/5/12.
 */
public class DeadLockChecker {

    private final static ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();
    final static Runnable deadLockChecker = new Runnable() {
        @Override
        public void run() {
            while (true){
                long[] deadlockedThreads = mxBean.findDeadlockedThreads();
                if(deadlockedThreads != null){
                    ThreadInfo[] threadInfo = mxBean.getThreadInfo(deadlockedThreads);
                    for(Thread t:Thread.getAllStackTraces().keySet()){
                        for(int i=0;i<threadInfo.length;i++){
                            if(t.getId() == threadInfo[i].getThreadId()){
                                t.interrupt();
                            }
                        }
                    }
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {}
            }
        }
    };

    public static void check(){
        Thread thread = new Thread(deadLockChecker);
        thread.setDaemon(true);
        thread.start();
    }
}
